package com.itcm.skymail.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcm.common.constant.ProductConstant;
import com.itcm.common.utils.PageUtils;
import com.itcm.common.utils.Query;
import com.itcm.skymail.product.dao.AttrDao;
import com.itcm.skymail.product.entity.*;
import com.itcm.skymail.product.service.*;
import com.itcm.skymail.product.vo.AttrRespVo;
import com.itcm.skymail.product.vo.AttrVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attrVo) {
        // 先保存attr
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.baseMapper.insert(attrEntity);
        // 销售类型没有属性分组信息
        if (attrVo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 再保存attr 和 attrGroup 的关联关系
            // 有分组信息的时候才添加关联关系
            if (attrVo.getAttrGroupId() != null) {
                AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
                relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
                relationEntity.setAttrId(attrEntity.getAttrId());
                attrAttrgroupRelationService.save(relationEntity);
            }
        }
    }

    @Override
    public PageUtils queryPageByCatId(String attrType, Map<String, Object> params, Long catelogId) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("attr_type", "base".equalsIgnoreCase(attrType) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        String key = (String) params.get("key");
        log.info("catelogId : {}", catelogId);
        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((obj) -> {
                obj.like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        PageUtils pageUtils = new PageUtils(page);

        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> newRecords = records.stream().map(attr -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attr, attrRespVo);
            if ("base".equalsIgnoreCase(attrType)) {
                // 根据attr的ID 查询出 分组ID
                AttrAttrgroupRelationEntity attrAttrGroup = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
                if (attrAttrGroup != null) {
                    if (attrAttrGroup.getAttrGroupId() != null) {
                        // 获取到分组ID
                        AttrGroupEntity attrGroup = attrGroupService.getById(attrAttrGroup.getAttrGroupId());
                        attrRespVo.setGroupName(attrGroup.getAttrGroupName());
                    }
                }
            }
            if (attr.getCatelogId() != null) {
                // 查分类名
                CategoryEntity category = categoryService.getById(attr.getCatelogId());
                attrRespVo.setCatelogName(category.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(newRecords);
        return pageUtils;
    }

    @Override
    public AttrRespVo getDetailById(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity, attrRespVo);
        if (attrEntity.getCatelogId() != null) {
            List<Long> path = categoryService.getCategoryPathById(attrEntity.getCatelogId());
            attrRespVo.setCatelogPath(path);
        }

        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            try {
                attrAttrgroupRelationEntity = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            } catch (Exception e) {
                throw new RuntimeException("根据属性ID获取属性分组出错，数据有误");
            }
            if (attrAttrgroupRelationEntity != null) {
                attrRespVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
            }
        }
        return attrRespVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attrVo) {
        // 先更新主表
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.updateById(attrEntity);

        QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId());
        if (attrVo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 再更新关联关系

            int relationCount = attrAttrgroupRelationService.count(wrapper);
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrVo.getAttrId());
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            if (relationCount > 0) {
                // update relation
                attrAttrgroupRelationService.update(relationEntity, wrapper);
            } else {
                // insert realtion
                attrAttrgroupRelationService.save(relationEntity);
            }
        } else {
            // 如果为基本属性 变更 为销售属性  则要删除关联关系
            attrAttrgroupRelationService.remove(wrapper);
        }
    }

    @Transactional
    @Override
    public void removeCasByIds(List<Long> attrIds) {
        this.removeByIds(attrIds);
        // 删除关联关系
        attrAttrgroupRelationService.remove(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_id", attrIds));
    }

    @Override
    public List<ProductAttrValueEntity> listForSpuBySpuId(Long spuId) {
        QueryWrapper<ProductAttrValueEntity> wrapper = new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId);
        List<ProductAttrValueEntity> list = productAttrValueService.list(wrapper);
        return list;
    }

    @Transactional
    @Override
    public void updateProductAttrValueBySpuId(Long spuId, List<ProductAttrValueEntity> productAttrValueEntities) {
        /*
        因为前端体检的是整个spu对应的规格参数的所有数据 所以没有必要一个个更新
        可以 先删除 再添加
         */
        QueryWrapper<ProductAttrValueEntity> wrapper = new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId);

        productAttrValueService.remove(wrapper);

        List<ProductAttrValueEntity> collect = productAttrValueEntities.stream().map(item -> {
            item.setSpuId(spuId);
            return item;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(collect);
    }

    @Override
    public List<Long> filterSearchAttrIds(List<Long> baseAttrIds) {
        return this.baseMapper.filterSearchAttrIds(baseAttrIds);
    }
}